import { inject, observer } from 'mobx-react';
import { Checkbox, Row, Col, Button, Breadcrumb, Table } from 'antd';

const CheckboxGroup = Checkbox.Group;
import { WeaTop, WeaRightMenu, WeaTab, WeaSearchGroup, WeaFormItem, WeaTools, WeaEchart, WeaSelect, WeaNewScroll, WeaDialog } from 'ecCom';
import { WeaSwitch } from 'comsMobx';
import { toJS } from 'mobx';

const getKey = WeaTools.getKey;
import { getRandColorCode } from '../util/index';
import EchartMap from './addressComp/mapChart';
import EchartPie from './addressComp/pieChart';
import ReportEchartAlert from '../public/report-echart-alert';
import equals from 'deep-equal';
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

const colorAttr = ['#635B8C', '#0A2736', '#319A96', '#A8909B', '#F60E6E', '#4CAC35', '#AA8CB2', '#1FA090',
  '#2F34E8', '#333493', '#934849', '#B04230', '#F0FDC9', '#957639', '#F1174B', '#FD6997', '#4860CF', '#22DC36',
  '#8A7661', '#961FAE', '#30B405', '#D61416', '#FE9717', '#6D07A2', '#7EC65B', '#64BD37', '#A4C23D', '#6F6101',
  '#406787', '#C1F4B8', '#F96C2F', '#C5BB90', '#8C485E', '#7B1202', '#549B5E', '#FA4CB9', '#AB86C3', '#C617E8',
  '#9DDD15', '#57F9AE', '#4342AA', '#31B3FF', '#CEA3DF', '#EC16AB', '#7411AD', '#B91B42', '#F21901', '#F6A618'];

@inject('addressChartStore')
@observer
class AddressChart extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      moveid: '',
    };
  }

  componentWillReceiveProps(nextProps) {
    if (!equals(this.props.datas, nextProps.datas)) {
      proParams = {};
    }
    const keyOld = this.props.location.key;
    const keyNew = nextProps.location.key;
    // 点击菜单路由刷新组件
    if (keyOld !== keyNew) {
      this.reset();
    }
  }

  componentDidMount() {
    const store = this.props.addressChartStore;
    store.initData();
    store.doSearch();
  }

  componentDidUpdate() {
    // 处理高级搜索类型栏单行展示--可能组件后续会支持了就不要了
    jQuery('.formItem-checkbox-group').parent('.wea-form-cell').css({ width: '100%' });
    jQuery('.formItem-checkbox-group .ant-col-6').css({ width: '12.5%' });
  }

  render() {
    const store = this.props.addressChartStore;
    const { showSearchAd, options, mapDatas, loading, pieDatas, currentProName, selectProvince, totalValue, dialogParams } = store;
    const pageHeight = `${this.state.pageHeight}px`;
    return (
      <WeaRightMenu
        ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@wr8png`}
        datas={this.getRightMenu()}
        collectParams={{
          favname: getLabel(1220, '地理分布'),
          favouritetype: 4,
          importantlevel: 1,
          objid: -1,
        }}
      >
        <WeaTop
          ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@7lg9bu`}
          loading={loading}
          title={getLabel(1220, '地理分布')}
          icon={<i className="icon-coms-crm" />}
          iconBgcolor="#96358a"
          showDropIcon
          buttonSpace={10}
          dropMenuDatas={this.getRightMenu()}
        >
          <WeaTab
            ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@usuyjl`}
            searchType={['advanced']}
            showSearchAd={showSearchAd}
            setShowSearchAd={(bool) => { store.setShowSearchAd(bool); }}
            searchsAd={this.formatForm()}
            buttonsAd={this.getAdButtons(this.props.ecId || '')}
            hasDropMenu
            advanceHeight={220}
          />
          <div className="crm-report-address">
            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@ixcp4n`} style={{ height: '100%' }} >
              <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@qw35g7`} xs={12} sm={14} md={16} lg={16} className="crm-report-h100 crm-report-bRight crm-report-parent" >
                <div className="crm-report-province">
                  <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@esoaov`} options={toJS(options)} value={selectProvince.provinceId} onChange={(v) => { store.searchCityCus(v); }} />
                </div>
                <div style={{ height: '100%', marginLeft: '15px' }}>
                  <EchartMap ecId={`${this && this.props && this.props.ecId || ''}_EchartMap@immexq`} ref="mapObj" datas={toJS(mapDatas)} provinceClick={(id) => { store.searchCityCus(id); }} />
                </div>
                <div className="crm-report-total">{getLabel(523, '总计')}：  {totalValue}</div>
              </Col>
              <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@jxxc4f`} xs={12} sm={10} md={8} lg={8} className="crm-report-h100 " >
                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@rmj94e`} className="crm-report-h50 crm-report-bBottom">
                  <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@870h40`} className="crm-report-h100" >
                    <div className="crm-report-right-header">
                      <Breadcrumb ecId={`${this && this.props && this.props.ecId || ''}_Breadcrumb@g3xuxg`}>
                        <Breadcrumb.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@krkgbn`}>{getLabel(84377, '饼图')}</Breadcrumb.Item>
                        <Breadcrumb.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@msn1uw`}>{currentProName}</Breadcrumb.Item>
                      </Breadcrumb>
                    </div>
                    <div className="crm-report-right-content">
                      {
                        pieDatas.length > 0 ?
                          <EchartPie ecId={`${this && this.props && this.props.ecId || ''}_EchartPie@q58x2i`} datas={toJS(pieDatas)} mouserover={(id) => { this.setState({ moveid: id }); }} />
                          :
                          <ReportEchartAlert ecId={`${this && this.props && this.props.ecId || ''}_ReportEchartAlert@sqjsdf`} loading={loading} />
                      }
                    </div>
                  </Col>
                </Row>
                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@jxolqn`} className="crm-report-h50">
                  <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@gs27b4`} className="crm-report-h100" >
                    <div className="crm-report-right-header">
                      <Breadcrumb ecId={`${this && this.props && this.props.ecId || ''}_Breadcrumb@lwuabe`}>
                        <Breadcrumb.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@esoql8`}>{getLabel(320, '列表')}</Breadcrumb.Item>
                        <Breadcrumb.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@2k0hjw`}>{currentProName}</Breadcrumb.Item>
                      </Breadcrumb>
                    </div>
                    <div className="crm-report-right-content">
                      <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@lj84lr`} height={'100%'}>
                        {
                          pieDatas.length > 0 ?
                            this.renderList(this.props.ecId || '')
                            :
                            <ReportEchartAlert ecId={`${this && this.props && this.props.ecId || ''}_ReportEchartAlert@k2o05a`} loading={loading} />
                        }
                      </WeaNewScroll>
                    </div>
                  </Col>
                </Row>
              </Col>
            </Row>
          </div>
        </WeaTop>
        <WeaDialog
          ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@0v5lr9`}
          icon="icon-coms-crm"
          iconBgcolor="#96358a"
          title={getLabel(20323, '客户信息')}
          visible={dialogParams.visible}
          url={dialogParams.url}
          onCancel={() => store.handleCustomersDialog(false)}
          style={{ width: 900, height: 600 }}
          buttons={[<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8g9glo@close`} type="primary" onClick={() => store.handleCustomersDialog(false)}>{getLabel(309, '关闭')}</Button>]}
        />
      </WeaRightMenu>
    );
  }

  getRightMenu() {
    const { addressChartStore } = this.props;
    const btnArr = [];
    btnArr.push({
    		icon: <i className="icon-coms-search " />,
      content: getLabel(2022, '重置'),
      key: '0',
      onClick: () => { this.reset(); },
    });
    	return btnArr;
  }

  reset() {
    const { addressChartStore } = this.props;
    addressChartStore.clearAdFields();
    addressChartStore.doSearch();
    this.refs.mapObj.refs.chart.clear();
    this.refs.mapObj.refs.chart.setState({ repaint: true });
  }

  getAdButtons(ecId) {
    const store = this.props.addressChartStore;
    return [
      (<Button ecId={`${ecId}_Button@gr2od4@search`} type="primary" onClick={() => { store.doSearch(); this.refs.mapObj.refs.chart.setState({ repaint: true }); store.setShowSearchAd(false); }}>{getLabel(197, '搜索')}</Button>),
      (<Button ecId={`${ecId}_Button@6k75vg@reset`} type="ghost" onClick={() => store.clearAdFields()}>{getLabel(2022, '重置')}</Button>),
      (<Button ecId={`${ecId}_Button@znw9gj@cancel`} type="ghost" onClick={bool => store.setShowSearchAd(false)}>{getLabel(201, '取消')}</Button>),
    ];
  }

  formatForm() {
    const store = this.props.addressChartStore;
    const { onChange, condition, form, customerTypeList, defaultValue } = store;
    const { isFormInit } = form;
    const formParams = form.getFormParams();
    const options = [];
    customerTypeList.map((type) => {
      options.push({ label: type.showname, value: type.key });
    });
    const group = [];
    isFormInit && toJS(condition).map((c,indexGroup) => {
      const items = [];
      c.items.map((fields) => {
        const hide = false;
        let dom;
        if (fields.domkey[0] == 'CustomerTypes') {
          const key = getKey(fields);
          const bindObj = form.$(key);
          items.push({
            com: (<WeaFormItem
              ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@0t2k54@${fields.domkey[0]}`}
              className="formItem-checkbox-group"
              label={`${fields.label}`}
              labelCol={{ span: `${fields.labelcol}` }}
              wrapperCol={{ span: `${fields.fieldcol}` }}
            >
              <CheckboxGroup ecId={`${this && this.props && this.props.ecId || ''}_CheckboxGroup@se7484@${fields.domkey[0]}`} options={options} value={[formParams[fields.domkey[0]]]} {...bindObj.bind()} />
            </WeaFormItem>),
          });
        } else {
          items.push({
            com: (<WeaFormItem
              ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@cf5oj6@${fields.domkey[0]}`}
              label={`${fields.label}`}
              labelCol={{ span: `${fields.labelcol}` }}
              wrapperCol={{ span: `${fields.fieldcol}` }}
            >
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@98bvn2@${fields.domkey[0]}`} fieldConfig={fields} form={form} onEnterSearch={this.onEnterSearch.bind(this)} />
            </WeaFormItem>),
          });
        }
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@4z9iw4@${indexGroup}`} needTigger title={c.title} col={2} showGroup={c.defaultshow} items={items} />);
    });
    return group;
  }

    renderList=(ecId) => {
      const arr = [];
      const { addressChartStore } = this.props;
      const { pieDatas, handleCustomersDialog } = addressChartStore;
      toJS(pieDatas).map((item,index) => {
        arr.push(<div data-index={item.id} className={`crm-report-right-list ${(this.state.moveid == item.id ? 'crm-report-right-list1' : '')}`}>
          <Row ecId={`${ecId}_Row@3g976h@${index}`}>
            <Col ecId={`${ecId}_Col@quoh2t@${index}`} span={6}>{item.name}</Col>
            <Col ecId={`${ecId}_Col@gq3iu7@${index}`} span={6}><span className="crm-report-right-list-detail" onClick={() => { handleCustomersDialog(true, item.id); }}>{item.value}</span></Col>
            <Col ecId={`${ecId}_Col@4akzfo@${index}`} span={6}>{item.precent}</Col>
            <Col ecId={`${ecId}_Col@55pxro@${index}`} span={6}><span className="crm-report-right-list-detail" onClick={() => { handleCustomersDialog(true, item.id); }}>{getLabel(17463, '明细')}</span></Col>
          </Row>
        </div>);
      });
      return arr;
    }

    onEnterSearch() {
      const { addressChartStore } = this.props;
      const { doSearch, setShowSearchAd, clearAdFields } = addressChartStore;
      doSearch();
      setShowSearchAd(false);
    }
}

export default WeaTools.tryCatch(React, props =>
  <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@gprc57`} msg={props.error ? props.error : getLabel(129417, '服务器运行出错，请联系系统管理员！')} />, { error: '' })(AddressChart);

